package com.gjh.xiaokabang2code.controller;
import com.gjh.xiaokabang2code.common.*;
import com.gjh.xiaokabang2code.model.request.LoginRt;
import com.gjh.xiaokabang2code.model.request.UpdateUserRt;
import com.gjh.xiaokabang2code.model.response.LoginRs;
import com.gjh.xiaokabang2code.model.response.SafetyUserRs;
import com.gjh.xiaokabang2code.service.UserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "${cors.origins}", allowCredentials = "true")
public class UserController {

    @Value("${cors.origins}")
    private String allowedOrigins;

    @Resource
    private UserService userService;

    public static final String SALT = "XiaoKabang2Bygjh2003";

    /**
     * 授权登录
     * @param loginRequest
     * @param httpServletRequest
     * @return
     * @throws Exception
     */
    @PostMapping("/uc")
    public BaseResponse<String> login(@RequestBody LoginRt loginRequest, HttpServletRequest httpServletRequest) throws Exception {
        String uId = loginRequest.getUId();
        if (uId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "登陆时学号为空(C1001)");
        }
        String uc = userService.login(uId, httpServletRequest);
        if (uc == null) {
            throw new BusinessException(ErrorCode.DATA_NULL, "返回登录凭证为空（C1002）");
        }
        return ResultUtils.success(uc);
    }

    @GetMapping("/current")
    public BaseResponse<SafetyUserRs> getCurrentUser(HttpServletRequest httpServletRequest) throws Exception {
        LoginRs loginUser = HttpSessionUtil.getLoginUser(httpServletRequest);
        if (loginUser == null) {
            return ResultUtils.error(ErrorCode.NOT_LOGIN, "未登录无法正常使用当前页面功能");
        }
        // todo 校验用户合法性
        SafetyUserRs safetyUser = userService.getSafetyUser(loginUser);
        if (safetyUser.getUc() == null) {
            return ResultUtils.error(ErrorCode.NOT_LOGIN, "未登录无法正常使用当前页面功能");
        }
        return ResultUtils.success(safetyUser);
    }

    @PostMapping("/update")
    public BaseResponse<String> updateUser(@RequestBody UpdateUserRt updateUserRt, HttpServletRequest httpServletRequest) throws Exception {
        LoginRs loginUser = HttpSessionUtil.getLoginUser(httpServletRequest);
        if (loginUser == null) {
            return ResultUtils.error(ErrorCode.NOT_LOGIN, "未登录无法正常使用当前页面功能");
        }
        // todo 校验用户合法性
        Boolean result = userService.updateUser(updateUserRt, loginUser);
        if (!result) {
            return ResultUtils.error(ErrorCode.DATA_NULL, "更新失败");
        }
        return ResultUtils.success("success");
    }
}
